package org.xxpay.pay.channel.chengzhi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;

@Service
public class ChengzhiPaymentService extends BasePayment {
    private final static String logPrefix = "【橙子支付】";
    @Override
    public String getChannelName() {
        return ChengzhiConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
        ChengzhiConfig config = new ChengzhiConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询易付通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String,Object> parameters = Maps.newHashMap();
        parameters.put("out_order_no", payOrderId);
        parameters.put("merchant", config.getAppId());
        parameters.put("sign", getSign(parameters, config.getPrivateKey()));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+ChengzhiConfig.REQ_PAY_QUERY_URL_FIXX, parameters, JSONObject.class);
        _log.info("{}易付查单同步请求响应参数：{}", logPrefix, origin.toJSONString());
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("respCode"), "000")) {
            // 橙子付订单支付状态：1-为已⽀支付，其它未⽀支付
            String payStatus = origin.getString("status");
            // 已支付
            if(StringUtils.equals("1", payStatus)) {
                retObj.put("status", 2);
            } else {
                // 支付中
                retObj.put("status", 1);
            }
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("out_order_no"));
            retObj.put("channelObj", origin.toJSONString());
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }

    //下单请求实现
    private JSONObject doOrderReq(PayOrder payOrder){
        ChengzhiConfig config = new ChengzhiConfig(getPayParam(payOrder));
        Map<String,Object> parameters = Maps.newHashMap();
        setParams(parameters,payOrder,config);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(parameters));
        // 将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        JSONObject retObj = new JSONObject();
        String payForm = HtmlUtils.form(config.getRequestUrl()+ChengzhiConfig.REQ_PAY_URL_FIXX, HtmlUtils.POST, parameters);
        return buildPayResultOfForm(retObj, payOrder, payForm);
    }

    /**
     * 设置支付请求参数
     * @param map
     * @param payOrder
     * @param config
     */
    private void setParams(Map<String,Object> map, PayOrder payOrder, ChengzhiConfig config){

        map.put("merchant", config.getAppId());
        map.put("amount", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        map.put("pay_code", config.getPayMode());
        map.put("order_no", payOrder.getPayOrderId());
        map.put("notify_url", payConfig.getNotifyUrl(getChannelName()));
        map.put("return_url", payOrder.getReturnUrl());
        map.put("sign", getSign(map,config.getPrivateKey()));

    }

    /**
     * 签名
     * @param parameters
     * @param key
     * @return
     */
    private String getSign(Map<String,Object> parameters,String key){
        String signTxt = SignUtils.parameterText(parameters);
        _log.info("{}易支付签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8);
        return sign;
    }

}
